package com.web.controller;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.web.base.Page;
import com.web.base.RestResult;
import com.web.model.Order;
import com.web.model.School;
import com.web.model.User;
import com.web.model.qo.WeiXinLogin;
import com.web.mapper.UserMapper;
import com.web.hotdata.HotDataStore;
import com.web.security.model.qo.AuthUserQo;
import com.web.security.service.IUserSecurityService;
import com.web.service.OrderService;
import com.web.service.SchoolService;
import com.web.service.UserService;
import com.web.service.WeiXinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/yqz/user")
@Api(tags = "登录相关操作")
public class UserController {

    private final Logger log = LoggerFactory.getLogger(getClass());
    private final HotDataStore hotDataStore;

    private final UserMapper mapper;
    private final UserService service;
    private final IUserSecurityService userSecurityService;

    private final OrderService orderService;
    private final SchoolService schoolService;
    private final WeiXinService weiXinService;

    @ApiOperation("微信登录,没有就会默认录入信息")
    @ResponseBody
    @PostMapping("/wxLogin")
    public RestResult<Object> getUserInfo(@RequestBody WeiXinLogin info, HttpSession session) throws Exception {
        try {
            log.info("inMap:" + JSON.toJSONString(info));
            Map<String,Object> userInfo = (Map<String,Object>) info.getUserInfo();
            String code = info.getCode().trim();;
            String openid = weiXinService.getOpenId(code);
            if (openid.equals("")){
                return RestResult.error("授权失败");
            }
            String nickName = weiXinService.filterEmoji(MapUtils.getString(userInfo,"nickName"),"");
            int gender = (int) MapUtils.getObject(userInfo,"gender");
            String language = MapUtils.getString(userInfo,"language");
            String city = MapUtils.getString(userInfo,"city");
            String province = MapUtils.getString(userInfo,"province");
            String country = MapUtils.getString(userInfo,"country");
            String avatarUrl = MapUtils.getString(userInfo,"avatarUrl");
            User user_info = service.selectByOpenId(openid);
            if (Validator.isNotNull(user_info)){
                user_info.setNickName(nickName);
                user_info.setGender(gender);
                user_info.setLanguage(language);
                user_info.setCity(city);
                user_info.setProvince(province);
                user_info.setCountry(country);
                user_info.setAvatarUrl(avatarUrl);
                user_info.setLastLoginTime(new Date());
                int i = service.update(user_info);
                if (i < 1){
                    return RestResult.error("更新用户信息失败！");
                }
                return RestResult.success("登录成功",weiXinService.wxLogin(user_info));
            }else {
                User user = new User();
                user.setOpenId(openid);
                user.setNickName(nickName);
                user.setGender(gender);
                user.setLanguage(language);
                user.setCity(city);
                user.setProvince(province);
                user.setCountry(country);
                user.setAvatarUrl(avatarUrl);
                user.setLastLoginTime(new Date());
                user.setCreditScore(Double.valueOf(100));
                user.setRegisterStatus(1);
                int i = service.insert(user);
                if (i < 1){
                    return RestResult.error("保存用户信息失败！");
                }
                return RestResult.success("登录成功",weiXinService.wxLogin(user));
            }
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return RestResult.error("登录异常！");
        }
    }

    @ApiOperation("微信登录,没有就会默认录入信息")
    @ResponseBody
    @GetMapping("/signOut")
    public RestResult<Object> signOut(HttpServletRequest request) throws Exception {
        try {
            weiXinService.loginOut(request);
        }catch (Exception e){
            // ignore
        }
        return RestResult.success("退出成功");
    }

    @ApiOperation("账号密码登录")
    @ResponseBody
    @PostMapping("/signIn")
    public RestResult<Object> getUserInfo(@Validated @RequestBody AuthUserQo info, HttpSession session) throws Exception {
        String username = info.getUsername();
        String key = "";
        if (Validator.isMobile(username)){
            key = "phone";
        }else {
            key = "userId";
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo(key,username);
        List<User> userList = mapper.selectByExample(example);
        if (userList.size() < 1 ){
            return RestResult.error("用户不存在");
        }
        info.setUsername(String.valueOf(userList.get(0).getUserId()));
        return RestResult.success("登录成功",userSecurityService.login(info) );
    }

    @ApiOperation("获取用户信息列表")
    @PreAuthorize("hasAnyRole('admin')")
    @ResponseBody
    @PostMapping("/query")
    public RestResult<Object> getUserList(@RequestBody Page<User> info, HttpSession session) throws Exception {
        Example example = returnQueryExample(info.getQueryObj());
        com.github.pagehelper.Page<User> page = PageHelper.startPage(info.getCurrPage() == 0 ? 1 : info.getCurrPage(),info.getPageSize() == 0 ? 100:info.getPageSize());
        List<User> list = mapper.selectByExample(example);
        PageInfo<User> pageInfo =  new PageInfo<>(page.getResult());
        if (list.size() < 1){
            return RestResult.error("查询为空");
        }
        return RestResult.success("查询成功",pageInfo);
    }

    @ApiOperation("获取用户信息列表")
    @ResponseBody
    @PostMapping("/queryOne")
    public RestResult<Object> queryOne(@RequestBody User info, HttpSession session) throws Exception {
        Example example = returnQueryExample(info);
        List<User> list = mapper.selectByExample(example);
        if (list.size() < 1){
            return RestResult.error("查询为空");
        }
        return RestResult.success("查询成功",list.get(0));
    }


    /**
     * 查询 Example
     * @param user
     * @return
     */
    public Example returnQueryExample(User user){
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (Validator.isNotNull(user)){
            if (Validator.isNotNull(user.getUserId())){
                criteria.andEqualTo("schoolId",user.getSchoolId());
            }
            if (Validator.isNotNull(user.getOpenId())){
                criteria.andEqualTo("openId",user.getOpenId());
            }
            if (Validator.isNotNull(user.getUserNbr())){
                criteria.andEqualTo("userNbr",user.getUserNbr());
            }
            if (Validator.isNotNull(user.getNickName())){
                criteria.andLike("nickName", "%" + user.getNickName() + "%");
            }
            if (Validator.isNotNull(user.getRealName())){
                criteria.andLike("realName", "%" + user.getRealName() + "%");
            }
            if (Validator.isNotNull(user.getGender())){
                criteria.andLike("gender", "%" + user.getGender() + "%");
            }
            if (Validator.isNotNull(user.getGrade())){
                criteria.andEqualTo("gender", user.getCountry());
            }
            if (Validator.isNotNull(user.getPhone())){
                criteria.andLike("phone","%" +  user.getPhone() + "%");
            }
            if (Validator.isNotNull(user.getRegisterId())){
                criteria.andEqualTo("registerId",  user.getRegisterId());
            }
            if (Validator.isNotNull(user.getRegisterStatus())){
                criteria.andEqualTo("registerStatus",  user.getRegisterStatus());
            }
            if (Validator.isNotNull(user.getSchoolId())){
                criteria.andEqualTo("schoolId",  user.getSchoolId());
            }
            if (Validator.isNotNull(user.getSchoolName())){
                criteria.andLike("schoolName",  "%" + user.getSchoolName() + "%");
            }
            if (Validator.isNotNull(user.getColleges())){
                criteria.andLike("colleges",  "%" + user.getColleges() + "%");
            }
            if (Validator.isNotNull(user.getUserId())){
                criteria.andEqualTo("userId",  user.getUserId());
            }
        }
        return example;
    }

    @RequestMapping("/remove")
    @ResponseBody
    public RestResult<Object> remove (@RequestBody User info,HttpServletRequest request){
        if (!Validator.isNotNull(info) || !Validator.isNotNull(info.getUserId())){
            return RestResult.error("用户id不能为空");
        }
        User user = service.selectById(info.getUserId());
        if (!Validator.isNotNull(user)){
            return RestResult.error("用户id不正确");
        }
        List<Order> orderList = orderService.selectByUid(user.getUserId());
        if (Validator.isNotNull(orderList)){
            for (Order o:orderList) {
                if (o.getOrderStatus() == 1){
                    return RestResult.error("用户还有在途单未完成");
                }
            }
        }
        int i = service.delete(user);
        if (i < 1){
            return RestResult.error("删除失败");
        }
        return RestResult.success("删除成功");
    }


    @ApiOperation("更新用户信息")
    @RequestMapping("/upData")
    @ResponseBody
    public RestResult<Object> upData(@RequestBody User info,HttpServletRequest request){
        if (!Validator.isNotNull(info) || !Validator.isNotNull(info.getUserId())){
            return RestResult.error("输入信息不完整");
        }
        User user = service.selectById(info.getUserId());
        if (!Validator.isNotNull(user)){
            return RestResult.error("无效的用户信息");
        }
        if (Validator.isNotNull(info.getPhone())){
            if (!Validator.isMobile(info.getPhone())){
                return RestResult.error("号码格式不对");
            }
            user.setPhone(info.getPhone());
        }
        if (Validator.isNotNull(info.getNickName())){
            user.setNickName(info.getNickName());
        }
        if (Validator.isNotNull(info.getRealName())){
            user.setRealName(info.getRealName());
        }
        if (Validator.isNotNull(info.getRegisterStatus())){
            user.setRegisterStatus(info.getRegisterStatus());
        }
        if (Validator.isNotNull(info.getColleges())){
            user.setColleges(info.getColleges());
        }
        if (Validator.isNotNull(info.getSchoolId())){
            School school = schoolService.selectById(info.getSchoolId());
            if (!Validator.isNotNull(school)){
                return RestResult.error("无效的学校ID");
            }
            user.setSchoolId(school.getSchoolId());
            user.setSchoolName(school.getSchoolName());
        }
        if (Validator.isNotNull(info.getGrade())){
            user.setGrade(info.getGrade());
        }
        int i = service.update(user);
        if ( i < 1){
            return RestResult.error("更新失败");
        }
        return RestResult.success("跟新成功");
    }

}
